package TestPaperSystem.utils.compiler;


import lombok.Data;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Callable;

@Data
public class StringCompiler {

    private static StringCompiler stringCompiler;

    public static StringCompiler getInstance(){
        if(stringCompiler == null)
            stringCompiler = new StringCompiler();
        return stringCompiler;
    }


    public void saveJavaFile(String fileName, String code, String demo) throws IOException{
        String curDir = "D:\\tempFile";

        int index = code.indexOf("System.in");
        String item = " new ByteArrayInputStream(\""+ demo +"\".getBytes(StandardCharsets.UTF_8))";
        code = "import java.io.*;\n" +
                "import java.nio.charset.StandardCharsets;\n" +
            code.substring(0,index) + item + code.substring(index + 9 , code.length());

        fileName = curDir + "\\" + fileName;
        File file = new File(fileName);

        if(file.exists()){
            file.delete();

            String tmp = fileName.toLowerCase();
            int pos = tmp.indexOf(".java");

            if(pos >= 0){
                tmp = tmp.substring(0,pos) + ".class";
                file = new File(tmp);
                if(file.exists())
                    file.delete();
            }

        }
        FileWriter fw = new FileWriter(fileName);
        fw.write(code);
        fw.close();
    }

    public String runFile() throws IOException {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

        int result = compiler.run(null , null , null , "D:/tempFile/Main.java");

        if(result == 0){
            Runtime run = Runtime.getRuntime();
            StringBuilder stringBuilder = new StringBuilder();
            Process process = run.exec("java -cp D:/tempFile/ Main");
            InputStream is = process.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(is));

            String info = "";
            while((info = br.readLine()) != null){
                stringBuilder.append(info);
            }
            is.close();
            br.close();
            return stringBuilder.toString();
        }else
            return null;

    }

    public synchronized float actualScore(String fileName, String code, String demo , String result_db ){
        String result;
        try {
            this.saveJavaFile(fileName , code , demo);
            result = this.runFile();
        } catch (IOException e) {
            return 0;
        }

        if(result == null){
            return 0;
        }else{
            return result.equals(result_db) ? 1.0f : 0.2f;
        }

    }

}
